package com.hulk.dryad.admin.controller.other;

import com.fujieid.jap.sso.JapMfa;
import com.fujieid.jap.sso.JapMfaService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hulk.dryad.admin.api.vo.OtpVO;
import com.hulk.dryad.common.annotation.PrintlnLog;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.SecurityUtils;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.admin.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** @Author hulk
 *  @Date 2019/12/15
 *
 */

@ApiSort(3)
@Api(value = "totp", tags = "TOTP验证码")
@RequestMapping("/totp")
@RestController
@RequiredArgsConstructor
public class TotpAuthCodeController {


  private final SysUserService sysUserService;

  private final JapMfaService japMfaService;


	/**
	 * 获取用户TOTP明文
	 *
	 */
	@PrintlnLog
	@ApiOperation(value = "codeInfo", notes = "获取用户TOTP明文")
	@ApiOperationSupport(order = 1)
	@GetMapping("/code/info")
	public R codeInfo()  {
		String username = SecurityUtils.getUser().getUsername();
		SysUserModel sysUser = sysUserService.getUserByName(username);
		if (sysUser == null) {
			return R.failed(BEC.E_2015);
		}
		JapMfa japMfa = new JapMfa(japMfaService);
		String img = japMfa.getOtpQrcodeFileBase64(username, CommonConstants.BACK_END_PROJECT, true);
		String totp = sysUser.getTotp();
		OtpVO otpVo = new OtpVO();
		otpVo.setImg(img);
		otpVo.setTotp(totp);
		return R.ok(otpVo);
	}

	/**
	 * 获取用户TOTP明文
	 *
	 */
	@PrintlnLog
	@ApiOperation(value = "codeInfo", notes = "获取用户TOTP明文")
	@GetMapping("/code/info/{userId}")
	public R userCodeInfo(@PathVariable Long userId)  {
		SysUserModel sysUser = sysUserService.getById(userId);
		if (sysUser == null) {
			return R.failed(BEC.E_2015);
		}
		String totp = sysUser.getTotp();
		OtpVO otpVo = new OtpVO();
		otpVo.setTotp(totp);
		return R.ok(otpVo);
	}

}
